import 'package:cunyutech_flutter_core/cunyutech_flutter_core.dart';
import 'package:cunyutech_flutter_ui/src/text/main.dart';
import 'package:cunyutech_flutter_ui/src/theme/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' hide RefreshCallback;

import 'SliverListView.dart';
import 'SmilarListEmpty.dart';
import 'SmilarListViewFooter.dart';

class SmilarListView extends StatefulWidget {
  SmilarListView({
    Key key, 
    this.data, 
    this.renderItem, 
    this.renderRefresh, 
    this.onRefresh, 
    this.refreshIndicatorExtent = _defaultRefreshIndicatorExtent,
    this.refreshTriggerPullDistance = _defaultRefreshTriggerPullDistance,
    this.onEndReached, 
    this.endReachedTriggerDistance = _defaultEndReachedTriggerDistance,
    this.onEndReachedStateChange, 
    this.backgroundColor = Colors.transparent,
    this.footer, 
    this.header, 
    this.empty, 
    this.onScrollEnd,
    this.grid,
    this.gridDelegate,
    this.noNetworkIcon,
    this.firstLoading,
    this.firstLoadingSkeleton,
  }) : super(key: key);

  /// 渲染列表项
  final SliverListViewRenderItemBuilderDelegate renderItem;
   /// 渲染下拉刷新器 可选
  final RefreshControlIndicatorBuilder renderRefresh;
  /// 列表数据
  final List<dynamic> data;
  /// 触发刷新事件 异步 可选
  final RefreshCallback onRefresh;
  /// 触发refresh零界点
  final double refreshIndicatorExtent;
  /// 触发refresh指示器的零界点
  final double refreshTriggerPullDistance;
  /// 触发上拉加载事件
  final EndReachedCallback onEndReached;
  // 触发endReached的零界点
  final double endReachedTriggerDistance;
  /// 列表尾部 可以渲染上拉加载组件
  final Widget footer;
  /// 头部
  final Widget header;
  /// 状态变更
  final EndReachedStateChange onEndReachedStateChange;
  /// 列表背景色，默认为透明色
  final Color backgroundColor;
  /// 滑动结束
  final VoidCallback onScrollEnd;

  /// 内容为空时显示
  final Widget empty;
  /// 是否为网格
  final bool grid;
  /// 网格代理
  final SliverGridDelegate gridDelegate;

  final String noNetworkIcon;

  /// 是否在加载过程中
  final bool firstLoading;
  /// 初次加载的骨架图
  final Widget firstLoadingSkeleton;

  static const double _defaultRefreshTriggerPullDistance = 100.0;
  static const double _defaultRefreshIndicatorExtent = 60.0;
  static const double _defaultEndReachedTriggerDistance = 10;

  static SliverListViewState of(BuildContext context){
    return context.dependOnInheritedWidgetOfExactType<SliverListViewState>();
  }

  static defaultFooter(bool hasMore) {
    return SmilarListViewFooter(
        hasMore: hasMore == true, 
        textStyle: TextStyle(fontSize: CYFontSize.Default),
    );
  }

  _SmilarListViewState createState() => _SmilarListViewState();
}

class _SmilarListViewState extends State<SmilarListView> {
  CYNetwork cyNetwork = CYNetwork();

  @override
  void initState() { 
    super.initState();
    cyNetwork.check((){
      setState(() {});
    });
  }

  @override
  void dispose() { 
    cyNetwork.dispose();
    super.dispose();
  }

  EndReachedState reachedState;
  @override
  Widget build(BuildContext context) {
    if(widget.firstLoading == true) {
      return widget.firstLoadingSkeleton;
    }
    List<Widget> listViewChildren = [];
    bool hasContent = true;
    listViewChildren.add(widget.header);

    if(cyNetwork.status == NetWorkStatus.Unknown) {
      listViewChildren.add(SmilarListEmpty(
        onTap: widget.onRefresh,
        icon: Image.asset(widget.noNetworkIcon, width: 163, fit: BoxFit.cover,),
        child: CYDescrition("网络连接失败\n请检查您的手机联网状态", maxLines: null, textAlign: TextAlign.center, alignment: Alignment.center),
      ));
    } else if(widget.data == null || widget.data.isEmpty) {
      listViewChildren.add(widget.empty);
      hasContent = false;
    } else {
      List<Widget> children = widget.data.map((item){
        return widget.renderItem(context, item, widget.data.indexOf(item));
      }).toList();
      listViewChildren.addAll(children);
    }

    if(widget.grid != true && hasContent) {
      listViewChildren.add(widget.footer);
    }

    Widget view;
    if(widget.grid != true || !hasContent) {
      view = ListView(
        controller: PrimaryScrollController.of(context),
        children: listViewChildren.where((item)=> item != null).toList(),
      );
    } else {
      view = GridView(
        controller: PrimaryScrollController.of(context),
        gridDelegate: widget.gridDelegate,
        children: listViewChildren.where((item)=> item != null).toList(),
      );
    }

    return  SliverListViewState(
      reachedState: reachedState,
      context: context,
      child: CupertinoPageScaffold(
        backgroundColor: widget.backgroundColor,
        child: EndReachedNotificationListenerBuilder (
          endReachedTriggerDistance: widget.endReachedTriggerDistance,
          onEndReached: widget.onEndReached,
          onEndReachedStateChange: widget.onEndReachedStateChange,
          onScrollEnd: widget.onScrollEnd,
          child: RefreshIndicator(
            onRefresh: widget.onRefresh,
            child: view,
          )
        )
      )
    );
  }
}
